package com.chx.service.Impl;

import com.chx.constant.MessageConstant;
import com.chx.constant.StatusConstant;
import com.chx.context.BaseContext;
import com.chx.dto.RolesDto;
import com.chx.entity.Roles;
import com.chx.exception.AccountNotPowerException;
import com.chx.exception.DeletionNotAllowedException;
import com.chx.mapper.PermissionMapper;
import com.chx.mapper.RoleMapper;
import com.chx.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author cp-月入过万
 * @Date 2025/5/29
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper  permissionMapper;
    @Override
    public List<Roles> getAllRoles() {
        return roleMapper.getAllRoles();
    }

    @Override
    public void save(RolesDto rolesDto) {
        Roles roles = new Roles();
        BeanUtils.copyProperties(rolesDto, roles);
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
            roleMapper.insert(roles);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public void update(RolesDto rolesDto) {
        Roles roles = new Roles();
        BeanUtils.copyProperties(rolesDto, roles);
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
            roleMapper.update(roles);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        //角色有没有关联用户
        if(roleMapper.getUserCountByRoleId(id) > 0)
            throw new DeletionNotAllowedException(MessageConstant.DELETE_USER_RELATED);
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN)){
            permissionMapper.delete(id);
            roleMapper.delete(id);
        }
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public Roles getById(Long id) {
        return roleMapper.getById(id);
    }
}
